# --**coding:utf-8**--

import logging,uuid,paramiko,time,config
from qaStatistic.models import ApiStats,Suppliers,SupplierApiStatistics,SupplierServices
from django.http import JsonResponse

def register(ip,port,user,pwd):
    '''注册ssh客户端，返回ssh对象'''
    sshClient = paramiko.SSHClient()
    sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sshClient.connect(ip, port=port, username=user, password=pwd)
    return sshClient

def timeFormat():
    '''时间格式化'''
    localTime = time.localtime(time.time()) # 获取当前时间
    strTime = time.strftime("%Y-%m-%d"+"T",localTime) # 格式化
    return strTime

def timeFormat2():
    '''时间格式化'''
    localTime = time.localtime(time.time())  # 获取当前时间
    strTime = time.strftime("%Y%m%d", localTime)  # 格式化
    return strTime

def checkChannelParms(channelName,interfaceName,date):
    try:
        if channelName == '':
            config.parms['reason'] = config.errorInfo.get('channel')
            return config.parms
        elif interfaceName == '':
            config.parms['reason'] = config.errorInfo.get('interface')
            return config.parms
        elif date == '':
            config.parms['reason'] = config.errorInfo.get('date')
            return config.parms
        else:
            return True
    except Exception as exception:
        raise exception

def checkInterfaceParms(serviceIp,interfaceName,date,appID):
    try:
        if serviceIp == '':
            config.parms['reason'] = config.errorInfo.get('serveiceip')
            return config.parms
        elif interfaceName == '':
            config.parms['reason'] = config.errorInfo.get('interface')
            return config.parms
        elif date == '':
            config.parms['reason'] = config.errorInfo.get('date')
            return config.parms
        elif appID == '':
            config.parms['reason'] = config.errorInfo.get('appID')
            return config.parms
        else:
            return True
    except Exception as exception:
        raise exception
def queryLogFile(sshClient,filePath):
    try:
        conditions = "cd {0}; ls".format(filePath)
        stdin, stdout, stderr = sshClient.exec_command(conditions)
        file = str(stdout.read()).split('\n')
        filetype = type(str(stdout.read()).split('\n'))
        for i in range(len(file)):
            if 'cloud-api.'+timeFormat2() in file[i]:
                print 'find success:',file[i]
                return file[i]
            else:
                continue
    except Exception as e:
        raise e

def queryChannelLogFile(sshClient,filePath):
    try:
        conditions = "cd {0}; ls".format(filePath)
        stdin, stdout, stderr = sshClient.exec_command(conditions)
        file = str(stdout.read()).split('\n')
        filetype = type(str(stdout.read()).split('\n'))
        for i in range(len(file)):
            if 'cloud-facade-partner.'+timeFormat2() in file[i]:
                print 'find success:',file[i]
                return file[i]
            else:
                continue
    except Exception as e:
        raise e

def queryBusinessLogFile(sshClient,filePath):
    try:
        conditions = "cd {0}; ls".format(filePath)
        stdin, stdout, stderr = sshClient.exec_command(conditions)
        file = str(stdout.read()).split('\n')
        filetype = type(str(stdout.read()).split('\n'))
        for i in range(len(file)):
            if 'facade-19281.log' in file[i]:
                print 'find success:',file[i]
                return file[i]
            else:
                continue
    except Exception as e:
        raise e
def queryBusinessCloudApiLogFile(sshClient,filePath):
    try:
        conditions = "cd {0}; ls".format(filePath)
        stdin, stdout, stderr = sshClient.exec_command(conditions)
        file = str(stdout.read()).split('\n')
        filetype = type(str(stdout.read()).split('\n'))
        for i in range(len(file)):
            if 'cloud-api-19641.log' in file[i]:
                print 'find success:',file[i]
                return file[i]
            else:
                continue
    except Exception as e:
        raise e


def getLogid():
    # get logid
    return ''.join(str(uuid.uuid4()).split('-'))

# get supplier shortname
def getShortName(channelName):
    try:
        channelDbInfo = Suppliers.objects.get(name=channelName)
        return channelDbInfo.short_name

    except Exception as exception:
        raise exception

# gtet supplier id
def getSupplierId(channelName):
    try:
        channelDbInfo = Suppliers.objects.get(name=channelName)
        print channelDbInfo.id
        return channelDbInfo.id
    except Exception as exception:
        raise exception

# get supplierservices id
def getSupplierServicesID(supplierId,interfacename):
    # interfacename  --> 二次确认
    try:
        supplierService = SupplierServices.objects.filter(supplier_id=supplierId)
        for eachInfo in supplierService:
            if eachInfo.name == interfacename:
                return eachInfo.id
            elif eachInfo.name != interfacename:
                continue
            else:
                return None

    except Exception as exception:
        raise exception

def getHour(date):
    if len(date) == 10:
        return date[:8]+ ' '+date[8:11]
    else:
        return date

def registerBussiness(ip,user,pwd):
    '''注册ssh客户端，返回ssh对象'''
    sshClient = paramiko.SSHClient()
    sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # sshClient.connect('100.66.225.5', port=22, username='linkface', password='linkfaceRD')
    sshClient.connect(ip, username=user, password=pwd)
    return sshClient

class signLogger(object):
    '''注册logger'''
    def __init__(self,fileName):
        self.loger = logging.getLogger(__name__)
        self.fileName = fileName
    def getInfoLogger(self):

        infoLogger = logging.getLogger('linkfaceInfo')
        return infoLogger

    def getErrorLogger(self):

        errorLogger = logging.getLogger('linkfaceError')
        return errorLogger


class queryInterConditions(object): # 接口调用量查询条件
    def __init__(self,interfaceName,httpCode,queryPath,fileName,apiID='',requestTime=''):
        self.interfaceName = interfaceName
        self.httpCode = httpCode
        self.queryPath = queryPath
        self.apiId = apiID
        self.requestTime = timeFormat()+requestTime
        self.fileName = fileName

    # 判断使用哪个查询条件放在control控制，这里只提供所有的查询条件
    def queryByHttpCode(self):

        conditions = "cd {0};  cat {1} | grep {2} | grep {3} | wc -l".format(self.queryPath,self.fileName,self.interfaceName,self.httpCode)
        return conditions

    def queryByApiID(self):

        conditions = "cd {0};  cat {1} | grep {2} | grep {3} | wc -l".format(self.queryPath, self.fileName,self.interfaceName, self.apiId)
        return conditions
    def queryByReqeustTime(self):

        conditions = "cd {0};  cat {1} | grep {2} | grep {3} | wc -l".format(self.queryPath, self.fileName,self.interfaceName, self.requestTime)
        return conditions
    def queryByHttpCodeAndApiID(self):
        conditions = "cd {0};  cat {1} | grep {2} | grep {3} | grep {4}| wc -l".format(self.queryPath, self.fileName,
                                                                          self.interfaceName, self.httpCode,self.apiId)
        return conditions
    def queryByHttpCodeAndRequestTime(self):
        conditions = "cd {0};  cat {1} | grep {2} | grep {3} | grep {4}| wc -l".format(self.queryPath, self.fileName,
                                                                          self.interfaceName, self.httpCode,self.requestTime)
        return conditions

    def queryByApiIDdeAndRequestTime(self):
        conditions = "cd {0};  cat {1} | grep {2} | grep {3} | grep {4}| wc -l".format(self.queryPath, self.fileName,
                                                                          self.interfaceName, self.apiId,self.requestTime)
        return conditions
    def queryByAllConditions(self):
        conditions = "cd {0};  cat {1} | grep {2} | grep {3} | grep {4}| grep {5}| wc -l".format(self.queryPath, self.fileName,
                                                                                   self.interfaceName, self.httpCode,self.apiId,
                                                                                  self.requestTime)
        return conditions


class queryChannelConditions(object): # 渠道调用量查询条件
    def __init__(self,interfaceName,channelShortName,fileName,date):
        self.interfaceName = interfaceName
        self.channelShortName = channelShortName
        self.queryPath = config.channelPath
        self.fileName = fileName
        self.date = getHour(date)
    def queryChannelByAllCond(self):
        conditions = "cd {0};  cat {1} | grep {2} | grep {3} | grep '{4}'| wc -l".format(self.queryPath, self.fileName,
                                                                             self.interfaceName, self.channelShortName,self.date)
        return conditions

class queryBussinessConditions(object): # 业务日志查询
    def __init__(self,queryPath,fileName,requestID):

        self.queryPath = queryPath
        self.requestID = requestID
        self.fileName = fileName
        self.cloudApiPAth = config.businessCloudApiPath
        self.cloudApi_225 = config.interPath
        self.cloudFacade_225 = config.channelPath

    # 判断使用哪个查询条件放在control控制，这里只提供所有的查询条件
    def queryByRequestId(self): # 业务日志 --> facade

        conditions = "cd {0};  cat {1} | grep {2}".format(self.queryPath,self.fileName,self.requestID)
        return conditions

    def queryCloudApiByRequestID(self): # 业务日志 --> cloudApi

        conditions = "cd {0};  cat {1} | grep {2}".format(self.cloudApiPAth, self.fileName,self.requestID)
        return conditions

    def query225CloudApiByReqestID(self): # 225机器 --> cloudApi
        conditions = "cd {0};  cat {1} | grep {2}".format(self.cloudApi_225, self.fileName, self.requestID)
        return conditions

    def query225CloudFacadeByReqestID(self): # 225机器 --> facade
        conditions = "cd {0};  cat {1} | grep {2}".format(self.cloudFacade_225, self.fileName, self.requestID)
        return conditions

# query inter
class queryDB(object):
    def __init__(self,interfaceName,date,appid,requestTime=''):
        self.interfaceName = interfaceName
        self.date = date
        self.appid = appid
        self.requestTime = requestTime

    def queryDBByMustCon(self):

        queryResult = ApiStats.objects.filter(api=self.interfaceName,date=self.date,api_id=self.appid)
        return queryResult

# query channel
class queryChannelDB(object):

    def __init__(self,supplierID,supplierServiceID,date):
        self.supplierID = supplierID
        self.supplierServiceID = supplierServiceID
        self.date = date


    def querySupplierApiStatistics(self):
        print self.supplierID,self.supplierServiceID
        queryResult = SupplierApiStatistics.objects.get(supplier_id=self.supplierID,supplier_service_id=self.supplierServiceID,date=self.date)
        return queryResult
# class parameterCheck(object):
#
#     def __init__(self,requestInfo):
#         self.requestInfo = requestInfo
#
#     def interfaceParameterCheck(self):
#         for eachParameterKey in self.requestInfo.keys():
#             if eachParameterKey == '':
#                 return
